package org.stvd.controller.admin;

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.stvd.common.aspectj.lang.annotation.Log;
import org.stvd.common.aspectj.lang.enums.BusinessType;
import org.stvd.common.enums.UserLoginTypeEnum;
import org.stvd.common.security.SecurityUserHolder;
import org.stvd.common.utils.InterfaceResult;
import org.stvd.controller.BaseController;
import org.stvd.core.dto.SubmitResult;
import org.stvd.core.util.DateUtil;
import org.stvd.entities.admin.UserBase;
import org.stvd.entities.common.CodeTable;
import org.stvd.service.admin.UserBaseService;
import org.stvd.service.admin.UsersService;
import org.stvd.service.common.CodeTableService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 系统用户基本信息-控制类
 * @author houzx
 */
@Api(tags = "系统用户基本信息接口类")
@Controller
@RequestMapping("/admin/userbase")
public class UserBaseController extends BaseController {

    @Autowired
    UserBaseService userBaseService;
    @Autowired
    UsersService usersService;
    @Autowired
    CodeTableService codeTableService;

    @ApiIgnore
    @RequestMapping(value = "update/avatar", method = RequestMethod.POST)
    @ResponseBody
    public SubmitResult onAvatar(String userid, String avatar) throws Exception {
        SubmitResult submitResult = new SubmitResult();
        try {
            UserBase userBase = userBaseService.findByPk(UserBase.class, userid);
            if (userBase != null) {
                userBase.setAvatar(avatar.getBytes());
                userBase.setModifyTime(DateUtil.getSystemDate());
                userBase.setModifyUser(userid);
                userBaseService.update(userBase);
            } else {
                userBase = new UserBase();
                userBase.setUserId(userid);
                userBase.setNickName(SecurityUserHolder.getCurrentUserInfo().getUname());
                userBase.setAvatar(avatar.getBytes());
                userBase.setModifyTime(DateUtil.getSystemDate());
                userBase.setModifyUser(userid);
                userBaseService.insert(userBase);
            }
            updateSession(userBase);
            submitResult.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            submitResult.setMessage("修改头像失败！<br/>失败原因：" + e.getMessage());
        }
        return submitResult;
    }

    /**
     * @Description: 修改个人资料
     * @param map
     * @return
     * @throws Exception
     */
    @ApiIgnore
    @GetMapping(value = "edit")
    public String onLoad(ModelMap map) throws Exception {
        String userId = SecurityUserHolder.getCurrentUserId();
        UserBase userBase = userBaseService.findByPk(UserBase.class, userId);
        if (userBase == null) {
            userBase = new UserBase();
            userBase.setUserId(userId);
            userBase.setNickName(SecurityUserHolder.getCurrentUserInfo().getUname());
            userBase.setModifyUser(SecurityUserHolder.getCurrentUserInfo().getUserId());
            userBase.setModifyTime(DateUtil.getSystemDate());
        } else {
            if (userBase.getAreaNo()!=null && !"".equals(userBase.getAreaNo()) && userBase.getAreaNo().length() == 6) {
                userBase.setProvinceNo(userBase.getAreaNo().substring(0, 2) + "0000");
                userBase.setCityNo(userBase.getAreaNo().substring(0, 4) + "00");
                userBase.setRegionNo(userBase.getAreaNo());
            } else {
                userBase.setProvinceNo("000000");
                userBase.setCityNo("000000");
                userBase.setRegionNo("000000");
            }
        }
        map.put("userBase", userBase);
        String provID = (userBase.getProvinceNo().length() == 6) ? userBase.getProvinceNo().substring(0, 2) : "000000";
        String cityID = (userBase.getCityNo().length() == 6) ? userBase.getCityNo().substring(0, 4) : "000000";
        // 加载省、市、县区
        List<CodeTable> listAll = codeTableService.findAll("dic_native_place");
        map.put("listPro", codeTableService.getCodeTableListByRegExp(listAll, "^[0-9]{2}0000$"));
        map.put("listCity", codeTableService.getCodeTableListByRegExp(listAll, "^(?!("+provID+"0000))" + provID + "[0-9][0-9]00$"));
        map.put("listRegin", codeTableService.getCodeTableListByRegExp(listAll, "^(?!("+cityID+"00))" + cityID + "[0-9][0-9]$"));
        map.put("loginAccountList", SecurityUserHolder.getUserLoginAccount());
        map.put("loginAccountType", SecurityUserHolder.getUserLoginAccountType());
        map.put("loginMobile", SecurityUserHolder.getUserLoginMobile());
        map.put("loginEmail", SecurityUserHolder.getUserLoginAccount(UserLoginTypeEnum.Email.getValue()));
        return "/admin/users/UserBaseEdit.html";
    }

    @ApiOperation(value = "修改基本信息")
    @Log(title = "修改基本信息", businessType = BusinessType.UPDATE)
    @PostMapping(value = "edit")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onUpdateAction(
        @Valid @ModelAttribute("userBase") UserBase userBase, BindingResult bindingResult, ModelMap map) {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        if (bindingResult.hasErrors()) {
            result.setError(bindingResult.getAllErrors().get(0).getDefaultMessage());
            return result;
        }
        userBase.setModifyTime(DateUtil.getSystemDate());
        userBase.setModifyUser(SecurityUserHolder.getCurrentUserInfo().getUserId());
        userBaseService.updateUserBase(userBase);
        updateSession(userBase);

        map.clear();
        result.setMsg("修改成功!");
        return result;
    }

    private void updateSession(UserBase userBase) {
        if (userBase != null) {
            SecurityUserHolder.getCurrentUserDetail().setUserBase(userBase);
        }
        SecurityUserHolder.getCurrentUserInfo().setUname(userBase.getNickName());
    }
}